<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminBaseController;
use App\Models\AdminUser;
use Illuminate\Http\Request;

/**
 * 后台登录控制器
 * Class LoginController
 * @package App\Http\Controllers\Admin
 */
class LoginController extends AdminBaseController
{
    // 无需登录的方法
    protected $noNeedLogin = ['login'];

    // 无需鉴权的方法
    protected $noNeedRight = ['login', 'me', 'logout', 'refresh'];
    /**
     * 后台管理员登录
     */
    public function login()
    {
        $credentials = request(['username', 'password']);
        if (!$token = auth('admin')->attempt($credentials)) {
            return $this->fail('用户名或密码错误', 50008);
        }
        return $this->respondWithToken($token);
    }

    /**
     * 获取当前登录用户信息
     */
    public function me()
    {
        $me = auth('admin')->user();
        $roles = AdminUser::findOrFail($me->id)->getRoleNames();
        $me['roles'] = $roles;
        return $this->success($me);
    }

    /**
     * 退出登录
     */
    public function logout()
    {
        auth('admin')->logout();
        return $this->success();
    }

    /**
     * 刷新token
     */
    public function refresh()
    {
        $token = auth('admin')->refresh();
        return $this->respondWithToken($token);
    }
}
